import { Injectable } from '@nestjs/common';
// import { CreateSsdDto } from './dto/create-ssd.dto';
// import { UpdateSsdDto } from './dto/update-ssd.dto';

import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { SSDInfoDocumentType } from '../schema/SSD/ssd_schema';
@Injectable()
export class SsdService {
  constructor(
    @InjectModel('SSD_Info') private SsdModel: Model<SSDInfoDocumentType>,
  ) {}

  async createSsdInfo(body: any) {
    const ssd = new this.SsdModel(body);
    return ssd.save();
  }

  async getSsdInfo(query: any) {
    const { page, limit, price, capacity, order, interfaceType } = query;

    //处理排序
    let sort = {};
    if (order) {
      sort = { price: parseInt(order) };
    } else {
      sort = {};
    }

    //构建查询条件
    const filter: any = {};
    if (capacity) {
      filter.capacity = capacity;
    }
    if (interfaceType) {
      filter.interfaceType = interfaceType;
    }
    if (price) {
      if (price.min && !price.max) {
        filter.price = { $gte: price.min };
      } else if (!price.min && price.max) {
        filter.price = { $lte: price.max };
      } else if (price.min && price.max) {
        filter.price = { $gte: price.min, $lte: price.max };
      }
    }

    //执行查询
    const result = await this.SsdModel.find(filter)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort(sort)
      .exec();
    return {
      code: 200,
      msg: 'success',
      data: {
        result,
        total: await this.SsdModel.countDocuments(filter),
      },
    };
  }

  //通过id查询ssd信息
  async getSsdInfoById(id: string) {
    const result = await this.SsdModel.findById(id).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  //更新ssd信息
  async updateSsdInfo(id: string, body: any) {
    const result = await this.SsdModel.findByIdAndUpdate(id, body, {
      new: true,
    }).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  //删除ssd信息
  async deleteSsdInfo(id: string) {
    const result = await this.SsdModel.findByIdAndDelete(id).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  //获取所有ssd信息
  async getAllSsdInfo() {
    const result = await this.SsdModel.find().select('score price id').exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }
}
